<?php
/**
 * 分析菜单过滤逻辑
 */

$host = '113.44.136.17';
$port = 3306;
$database = 'qiandao';
$username = 'qiandao';
$password = 'NGbks3HWx5PhSxDX';

try {
    $pdo = new PDO("mysql:host={$host};port={$port};dbname={$database};charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "=== 菜单过滤逻辑分析 ===\n\n";
    
    // 查询所有启用的菜单，按 sort desc, id asc 排序
    $stmt = $pdo->query("SELECT id, pid, title, icon, node, url, sort, status FROM system_menu WHERE status = 1 ORDER BY sort DESC, id ASC");
    $menus = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "数据库查询结果（按 sort DESC, id ASC 排序）：\n";
    echo str_repeat("=", 80) . "\n";
    printf("%-5s %-5s %-20s %-6s %-25s %-20s\n", "ID", "PID", "标题", "SORT", "NODE", "URL");
    echo str_repeat("-", 80) . "\n";
    
    foreach ($menus as $menu) {
        printf("%-5s %-5s %-20s %-6s %-25s %-20s\n", 
            $menu['id'], 
            $menu['pid'], 
            mb_substr($menu['title'], 0, 18), 
            $menu['sort'],
            mb_substr($menu['node'], 0, 23),
            mb_substr($menu['url'], 0, 18)
        );
    }
    
    echo "\n" . str_repeat("=", 80) . "\n";
    echo "\n【关键发现】\n";
    echo "排序规则：sort DESC（降序）, id ASC（升序）\n";
    echo "- sort 值越大，排在越前面\n";
    echo "- sort 值相同时，id 越小，排在越前面\n\n";
    
    // 分析一级菜单
    echo "【一级菜单分析】\n";
    $topMenus = array_filter($menus, function($m) { return $m['pid'] == 0; });
    
    foreach ($topMenus as $menu) {
        echo "\n{$menu['title']} (ID:{$menu['id']}, SORT:{$menu['sort']})\n";
        
        // 统计子菜单
        $subCount = 0;
        foreach ($menus as $sub) {
            if ($sub['pid'] == $menu['id']) {
                $subCount++;
            }
        }
        
        echo "  子菜单数量: {$subCount}\n";
        echo "  URL: {$menu['url']}\n";
        echo "  图标: " . (empty($menu['icon']) ? '(无)' : $menu['icon']) . "\n";
        
        // 判断是否会被过滤
        $willBeFiltered = false;
        $reason = '';
        
        if ($subCount == 0 && (empty($menu['url']) || $menu['url'] === '#')) {
            $willBeFiltered = true;
            $reason = '没有子菜单且URL为空或#';
        }
        
        if ($willBeFiltered) {
            echo "  ❌ 会被过滤掉！原因：{$reason}\n";
        } else {
            echo "  ✓ 会显示\n";
        }
    }
    
    echo "\n\n【建议的 SORT 值分配】\n";
    echo "为了让所有菜单都能正常显示，建议设置如下 sort 值：\n";
    echo "- 打卡积分: 100\n";
    echo "- 权限管理: 90\n";
    echo "- 系统管理: 80\n";
    echo "- 微信管理: 70\n";
    echo "\n这样所有菜单都会按照业务重要性排序显示\n";
    
} catch (PDOException $e) {
    echo "数据库错误: " . $e->getMessage() . "\n";
}

